package net.mingsoft.flk.util;


import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ConnectionPoolTimeoutException;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpUtil {

    private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);
    private static final CloseableHttpClient httpclient = HttpClients.createDefault();
    private static final String userAgent = "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.87 Safari/537.36";
    /**
     * 发送HttpPost请求，参数为json字符串
     * @param url
     * @param jsonStr
     * @return
     */
    public static String sendPost(String url, String jsonStr) {
        // 字符串编码
        StringEntity entity = null;
        try {
            entity = new StringEntity(jsonStr, Consts.UTF_8.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 设置content-type
        entity.setContentType("application/json");
        HttpPost httpPost = new HttpPost(url);
//        // 防止被当成攻击添加的
//        httpPost.setHeader("User-Agent", userAgent);
        // 接收参数设置
        httpPost.setHeader("Accept", "application/json");
        httpPost.setEntity(entity);
        return getResponse(httpPost);
    }

    /**
     * 发送HttpPost请求，参数为map
     * @param url * 请求地址
     * @param map * 请求参数
     * @return 返回字符串
     */
    public static String sendPost(String url, Map<String, String> map) {
        // 设置参数
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        // 编码
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
        // 取得HttpPost对象
        HttpPost httpPost = new HttpPost(url);
        // 防止被当成攻击添加的
        httpPost.setHeader("User-Agent", userAgent);
        // 参数放入Entity
        httpPost.setEntity(formEntity);
        return getResponse(httpPost);
    }


    /**
     * 发送HttpGet请求
     * @param url  请求地址
     * @return 返回字符串
     */
    public static String sendGet(String url) {
        String result = null;
        CloseableHttpResponse response = null;
        try {
            HttpGet httpGet = new HttpGet(url);
            httpGet.setHeader("User-Agent", userAgent);
            response = httpclient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    /**
     * 发送不带参数的HttpPost请求
     *  @param url
     *  @return
     */
    public static String sendPost(String url) {
        String result = null;
        // 得到一个HttpPost对象
        HttpPost httpPost = new HttpPost(url);
        // 防止被当成攻击添加的
        httpPost.setHeader("User-Agent", userAgent);
        CloseableHttpResponse response = null;
        try {
            // 执行HttpPost请求，并得到一个CloseableHttpResponse
            response = httpclient.execute(httpPost);
            // 从CloseableHttpResponse中拿到HttpEntity
            HttpEntity entity = response.getEntity();
            // 将HttpEntity转换为字符串
            result = EntityUtils.toString(entity);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭CloseableHttpResponse
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;

    }




    /**
     * 初始化HttpClient
     * @param timeout
     * @return
     */
    private static CloseableHttpClient httpclient(Integer timeout){
        if (timeout==null){
            timeout=20000;
        }
        //设置请求配置
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(20000)//连接目标超时
                .setConnectionRequestTimeout(20000) //从连接池中获取连接的超时时间
                .setSocketTimeout(timeout).build();  //等待响应超时

        CloseableHttpClient httpclient = HttpClientBuilder.create()
                .setMaxConnTotal(200)                   //连接池中最大连接数
                /**
                 * 分配给同一个route(路由)最大的并发连接数。
                 * route：运行环境机器 到 目标机器的一条线路。
                 * 举例来说，我们使用HttpClient的实现来分别请求 www.baidu.com 的资源和 www.bing.com 的资源那么他就会产生两个route。
                 */
                .setMaxConnPerRoute(20)
                .setDefaultRequestConfig(requestConfig)
                .build();
        return httpclient;
    }

    /**
     * 获取HttpClient请求结果
     * @param httpPost
     * @return
     */
    private static String getResponse( HttpPost httpPost){
        CloseableHttpResponse response = null;
        String result = null;
        try {
            // 执行post请求
            response = httpclient(null).execute(httpPost);
            // 得到entity
            HttpEntity entity = response.getEntity();
           Integer status= response.getStatusLine().getStatusCode();
           if (status !=200){
                logger.error("求情失败.....");
           }
            // 得到字符串
            //注意 EntityUtils.toString()只能调用一次，否则会报错;
            result = EntityUtils.toString(entity);

        } catch (Exception e) {
            if (e instanceof HttpHostConnectException){
                logger.error("服务连接失败......");
            }
            if (e instanceof ConnectionPoolTimeoutException){
                logger.error("请求发起超时......");
            }
            if (e instanceof ConnectTimeoutException){
                logger.error("请求连接超时......");
            }
            if (e instanceof SocketTimeoutException){
                logger.error("请求响应超时......");
            }
           e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (Exception e) {
                    logger.error("关闭【CloseableHttpResponse】出错 ：Error -->>>"+e.getMessage());
                }
            }
        }
        return result;
    }

}
